package com.teziyou.commodity.web.jfinal;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.teziyou.commodity.model.AdvicedSSCat;
import com.teziyou.commodity.model.Dict;

public class AdvicedSSCatAction extends BaseController {
	
	public static final String sscat = "0220";
	
	public void index() {
		List<AdvicedSSCat> cats = AdvicedSSCat.dao.getAllAdvicedSSCat();
		
		//trees
		JSONArray array = loadTree(cats);
		setAttr("trees", array.toString());
		
		//target
		JSONArray targetArray = loadAdvicedTree(cats);
		setAttr("treesTarget", targetArray.toString());
		
		renderJsp("/WEB-INF/jsp/scenetype/index.jsp");
	}
	
	public void add() {
		String idStr = getPara("ids");
		if(StringUtils.isBlank(idStr)) 
			renderJson(fail("请选择要添加的分类！！"));
		else {
			String[] ids = idStr.split(",");
			for(String id:ids) {
				AdvicedSSCat cat = new AdvicedSSCat();
				cat.set("list_order", 0);
				cat.set("isOK", 1);
				cat.set("dictionary_id", id);
				cat.save();
			}
			renderJson(success("添加成功！！"));
		}
	}
	
	public void delete() {
		String idStr = getPara("ids");
		if(StringUtils.isBlank(idStr)) 
			renderJson(fail("请选择要删除的分类！！"));
		else {
			String[] ids = idStr.split(",");
			for(String id:ids) {
				AdvicedSSCat.dao.deleteById(id);
			}
			renderJson(success("删除成功！！"));
		}
	}
	
	public JSONArray loadAdvicedTree(List<AdvicedSSCat> cats) {
		JSONArray array = new JSONArray();
		for(AdvicedSSCat cat:cats) {
			JSONObject json = new JSONObject();
			int dictId = cat.getInt("dictionary_id");
			Dict d = Dict.dao.findById(dictId);
			json.put("id", d.getInt("DictionaryId"));
			json.put("pId", d.getInt("Dic_DictionaryId"));
			json.put("aid", cat.getInt("advicedspot_category_id"));
			json.put("name", d.getStr("Name"));
			json.put("open", true);
			array.add(json);
		}
		return array;
	}
	
	public JSONArray loadTree(List<AdvicedSSCat> cats) {
		List<Integer> ids = new ArrayList<>();
		for(AdvicedSSCat cat:cats) {
			int dictId = cat.getInt("dictionary_id");
			ids.add(dictId);
		}
		
		//trees
		List<Dict> dicts = Dict.dao.getDictsByType(sscat);
		JSONArray array = new JSONArray();
		for(Dict d:dicts) {
			JSONObject json = new JSONObject();
			int dictId = d.getInt("DictionaryId");
			if(ids.contains(dictId))
				continue;
			json.put("id", dictId);
			json.put("pId", d.getInt("Dic_DictionaryId"));
			json.put("name", d.getStr("Name"));
			json.put("open", true);
			array.add(json);
		}
		return array;
	}

}
